<?php

/**
 * 后台菜单控制器
 * @author yupoxiong<i@yufuping.com>
 */

namespace app\admin\controller;

use think\Request;
use app\admin\model\AdminMenu;

use app\admin\validate\AdminMenuValidate;

class AdminMenuController extends Controller
{

    public function index(AdminMenu $model)
    {

        $data = $model->order('sort_id asc, id asc')->column('*', 'id');
        // $this->initTree($data);
        // $menu = $this->getMenuData(0);
        $this->assign([
            'data' => json_encode($data)
        ]);
        return $this->fetch('index');
    }

    public function add(Request $request, AdminMenu $model, AdminMenuValidate $validate)
    {
        if ($request->isPost()) {
            $param           = $request->param();
            // dd($param);
            $validate_result = $validate->scene('add')->check($param);
            if (!$validate_result) {
                return error($validate->getError());
            }
            $result = $model::create($param);

            //如果
            if (isset($param['is_more']) && $param['is_more'] == 1) {
                $name = $param['more_name'];
                $url  = explode('/', $param['url']);
                $str  = '/';
                $data = [
                    [
                        'parent_id' => $result->id,
                        'name'      => '添加' . $name,
                        'url'       => $url[0] . $str . $url[1] . $str . 'add',
                        'icon'      => 'fa-plus',
                        'is_show'   => 0,
                        'log_method'  => 'POST',
                    ],
                    [
                        'parent_id' => $result->id,
                        'name'      => '修改' . $name,
                        'url'       => $url[0] . $str . $url[1] . $str . 'edit',
                        'icon'      => 'fa-pencil',
                        'is_show'   => 0,
                        'log_method'  => 'POST',
                    ],
                    [
                        'parent_id' => $result->id,
                        'name'      => '删除' . $name,
                        'url'       => $url[0] . $str . $url[1] . $str . 'del',
                        'icon'      => 'fa-trash',
                        'is_show'   => 0,
                        'log_method'  => 'POST',
                    ]
                ];

                $model->saveAll($data);
            }
            unset($url);
            $url = URL_CLOSE_REFRESH;
            if (isset($param['_create']) && $param['_create'] == 1) {
                $url = URL_RELOAD;
            }

            return $result ? success('添加成功', $url) : error();
        }
        $result = AdminMenu::order(['sort_id' => 'asc', 'id' => 'asc'])->column('id,parent_id,name,sort_id', 'id');
        $this->initTree($result);
        $parent_id = $request->param('parent_id') ?? 0;
        $selectData = $this->getMenuSelect(0, $parent_id);
        if ($parent_id == 0) {
            array_unshift($selectData, ['name' => '/', 'value' => 0, 'selected' => true]);
        } else {
            array_unshift($selectData, ['name' => '/', 'value' => 0]);
        }
        $select   = json_encode($selectData);
        $this->assign([
            'select'    => $select,
            'log_method' => $model->logMethod
        ]);

        return $this->fetch();
    }

    public function edit($id, Request $request, AdminMenu $model, AdminMenuValidate $validate)
    {

        $data = $model::find($id);
        if ($request->isPost()) {
            $param           = $request->param();
            $validate_result = $validate->scene('edit')->check($param);
            if (!$validate_result) {
                return error($validate->getError());
            }

            $result = $data->update($param);
            return $result ? success('修改成功', URL_CLOSE_REFRESH) : error();
        }
        $result = AdminMenu::order(['sort_id' => 'asc', 'id' => 'asc'])->column('id,parent_id,name,sort_id', 'id');
        $this->initTree($result);
        $parent_id = $data->parent_id;

        $selectData = $this->getMenuSelect(0, $parent_id);
        if ($parent_id == 0) {
            array_unshift($selectData, ['name' => '/', 'value' => 0, 'selected' => true]);
        } else {
            array_unshift($selectData, ['name' => '/', 'value' => 0]);
        }

        $select   = json_encode($selectData);
        $this->assign([
            'data'       => $data,
            'select'    => $select,
            'log_method' => $model->logMethod,
        ]);
        return $this->fetch('add');
    }

    public function del($id, Request $request, AdminMenu $model)
    {
        //判断是否有子菜单
        $have_son = $model->whereIn('parent_id', $id)->find();
        if ($have_son) {
            return error('有子菜单不可删除！');
        }

        if (count($model->noDeletionId) > 0) {
            if (is_array($id)) {
                if (array_intersect($model->noDeletionId, $id)) {
                    return error('ID为' . implode(',', $model->noDeletionId) . '的数据无法删除');
                }
            } else if (in_array($id, $model->noDeletionId)) {
                return error('ID为' . $id . '的数据无法删除');
            }
        }


        if ($model->softDelete) {
            $result = $model->whereIn('id', $id)->useSoftDelete('delete_time', time())->delete();
        } else {
            $result = $model->whereIn('id', $id)->delete();
        }

        return $result ? success('操作成功', URL_RELOAD) : error();
    }

    //菜单选择 select树形选择
    protected function menu($selected = 1, $current_id = 0)
    {
        $result = AdminMenu::where('id', '<>', $current_id)->order('sort_id', 'asc')->order('id', 'asc')->column('id,parent_id,name,sort_id', 'id');
        foreach ($result as $r) {
            $r['selected'] = (int)$r['id'] === (int)$selected ? 'selected' : '';
        }
        $str = "<option value='\$id' \$selected >\$spacer \$name</option>";
        $this->initTree($result);
        return $this->getTree(0, $str, $selected);
    }
    public function listData(Request $request, AdminMenu $model)
    {
        //查询所有菜单并以树的形式显示
        $data = $model->order('sort_id asc, id asc')->column('*', 'id');
        $this->initTree($data);
        $menu = $this->getMenuData(0);
        return json([
            'code' => 0,
            'msg'  => '获取成功',
            'data' => $menu,
        ]);
    }
}
